<template>
  <div class="main_box" style="padding: 10px">
    <div class="add_wrapper" v-loading="loading">
      <div class="title">基本信息</div>
      <el-form :model="dataForm" class="el-form__two" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <!-- 第1行 -->
          <el-form-item prop="businessId" label="商户">
            <el-select v-model="dataForm.businessId" @change="handleBusinessIdChange" clearable filterable>
              <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="departIds">
            <el-cascader v-model="dataForm.departIds" :options="departList" clearable :props="{ value: 'departId', label: 'departName', checkStrictly: true }"> </el-cascader>
          </el-form-item>
          <el-form-item label="货品类别" prop="serverType">
            <el-select v-model="dataForm.serverType" class="readonly" :disabled="$route.query.id || dataForm.huskFlag ? true : false">
              <el-option v-for="item in $Options.serverTypeList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="classifyIds" label="货品分类">
            <el-cascader :key="cascaderKey" filterable clearable v-model="dataForm.classifyIds" :options="treeThreeServerList" :props="{ label: 'classifyName', value: 'serverClassifyId' }"> </el-cascader>
          </el-form-item>

          <el-form-item prop="name" label="货品名称" placeholder="请输入货品名称">
            <el-input type="text" v-model="dataForm.name" clearable></el-input>
          </el-form-item>

          <el-form-item prop="businessClassifyIds" label="商户分类">
            <el-select
              class="business-classify_select"
              @change="handleBusinessClassifyChange"
              v-selectrichtext="{ ids: dataForm.businessClassifyIds, list: businessClassifyList }"
              v-model="dataForm.businessClassifyIds"
              clearable
              filterable
              multiple
            >
              <el-option v-for="item in businessClassifyList" :value="item.id" :label="item.name" :key="item.id">
                <div class="business-classify_name" v-html="item.name"></div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="ghModelId" label="可售时间模板">
            <el-select v-model="dataForm.ghModelId" @change="handleGhModelIdChange" clearable filterable>
              <el-option v-for="item in goodsHoursList" :label="item.modelName" :value="item.modelId" :key="item.modelId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="businessConfirmWay" label="商户确认方式:">
            <el-select v-model="dataForm.businessConfirmWay">
              <el-option v-for="item in $Options.businessConfirmWayList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="waiters" label="服务员:" v-if="dataForm.serverType == 4 && !dataForm.specs.length">
            <el-select v-model="dataForm.waiters" multiple value-key="id" @change="handleWaiterIdsChange">
              <el-option v-for="item in waiterList" :label="item.name" :value="item" :key="item.id" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="visitFlag" label="是否上门:">
            <el-radio-group v-model="dataForm.visitFlag" @change="handleFlagChange(1)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="shopFlag" label="是否到店:">
            <el-radio-group v-model="dataForm.shopFlag" @change="handleFlagChange(2)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="remoteFlag" label="是否远程:">
            <el-radio-group v-model="dataForm.remoteFlag" @change="handleFlagChange(3)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="fastFlag" label="紧急通知">
            <el-radio v-model="dataForm.fastFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.fastFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="backFlag" label="是否必须归还" v-show="dataForm.serverType == 3">
            <el-radio v-model="dataForm.backFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.backFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="dockingFlag" label="是否对接">
            <el-radio-group v-model="dataForm.dockingFlag" @change="dataForm.dockingType = ''">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="2">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="huskFlag" label="是否为空包产品">
            <el-radio v-model="dataForm.huskFlag" :label="1" :disabled="dataForm.serverId ? true : false">是</el-radio>
            <el-radio v-model="dataForm.huskFlag" :label="0" :disabled="dataForm.serverId ? true : false">否</el-radio>
          </el-form-item>
          <el-form-item prop="specDisplayType" label="多规格单项展示方式">
            <el-radio-group v-model="dataForm.specDisplayType" :disabled="specDisplayType">
              <el-radio :label="0">默认</el-radio>
              <el-radio :label="1">页面展示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="title" v-show="dataForm.dockingFlag == 2">对接信息</div>
      <el-form v-show="dataForm.dockingFlag == 2" :model="dataForm" class="el-form__two" label-width="200px">
        <el-row>
          <el-form-item prop="dockingType" label="对接类型" v-show="dataForm.dockingFlag == 2">
            <el-select
              v-model="dataForm.dockingType"
              @change="
                dataForm.doctorId = '';
                dataForm.itemCode = '';
              "
            >
              <el-option v-for="item in $Options.dockingTypeList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="doctorId" label="关联医生" v-show="dataForm.dockingType == 1">
            <el-select v-model="dataForm.doctorId" clearable filterable>
              <el-option v-for="item in doctorList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="itemCode" label="项目编码" v-show="dataForm.dockingType == 2">
            <el-input v-model="dataForm.itemCode" clearable> </el-input>
          </el-form-item>
          <el-form-item prop="itemName" label="项目名称" v-show="dataForm.dockingType == 2">
            <el-input v-model="dataForm.itemName" clearable> </el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="title" v-show="!dataForm.huskFlag">价格信息</div>
      <el-form v-show="!dataForm.huskFlag" :model="dataForm" class="el-form__two" ref="dataForm2" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="price" label="平台原价">
            <el-input type="number" :disabled="dataForm.serverType == 15 ? true : false" v-model.number="dataForm.price" @input="handleMoneyInput(0)" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item label="平台售价" prop="salePrice">
            <el-input type="number" :disabled="dataForm.serverType == 15 ? true : false" v-model.number="dataForm.salePrice" @input="handleMoneyInput(1)" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="marketPrice" label="商户原价">
            <el-input type="number" :disabled="dataForm.serverType == 15 ? true : false" v-model.number="dataForm.marketPrice" @input="handleMoneyInput(5)" @blur="handleMarketPriceBlur" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="discount" label="商户折扣比例">
            <el-input style="position: relative" type="number" v-model.number="dataForm.discount" @input="handleDiscountInput" @blur="handleDiscountBlur" clearable>
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item label="成本价" prop="costPrice">
            <el-input type="number" v-model.number="dataForm.costPrice" @input="handleMoneyInput(2)" @blur="handleCostBlur" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="externalDiscount" label="货品对外折扣">
            <el-input style="position: relative" type="number" v-model.number="dataForm.externalDiscount" @input="handleExternalDiscountInput" clearable>
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="relationAmountType" label="折扣金选择">
            <el-select v-model="dataForm.relationAmountType" multiple clearable filterable>
              <el-option v-for="item in subsidyAmountList" :key="item.value" :value="item.value" :label="item.label"> </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="stock" label="总库存">
            <el-input v-model="dataForm.stock" clearable @input="handleStockInput()"> </el-input>
          </el-form-item>
          <el-form-item label="押金" prop="deposit" type="number" v-if="dataForm.serverType == 3">
            <el-input type="number" v-model.number="dataForm.deposit" clearable @input="handleMoneyInput(4)">
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="packageFee" label="包装费">
            <el-input type="number" v-model.number="dataForm.packageFee" clearable @input="handleMoneyInput(3)">
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="packageFlag" label="包装费计算方式">
            <el-radio v-model="dataForm.packageFlag" :label="1">独立包装费</el-radio>
            <el-radio v-model="dataForm.packageFlag" :label="2">合并包装费</el-radio>
          </el-form-item>

          <el-form-item prop="deliveryFlag" label="是否需配送费">
            <el-radio v-model="dataForm.deliveryFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.deliveryFlag" :label="0">否</el-radio>
          </el-form-item>
        </el-row>
      </el-form>

      <div class="title" v-if="dataForm.ghModelId">可售时间</div>
      <el-row style="width: 96%; margin: 0 auto" v-if="dataForm.ghModelId">
        <el-table :data="dataForm.goodsHours" style="width: fit-content; max-width: fit-content; margin-bottom: 10px">
          <el-table-column type="index" label="序号" align="center" width="100px"> </el-table-column>
          <el-table-column prop="beginHours" label="开始时间" align="center" width="200"> </el-table-column>
          <el-table-column prop="endHours" label="结束时间" align="center" width="200"> </el-table-column>
          <el-table-column prop="estimateTime" label="最快到达时间" align="center" width="200">
            <template slot-scope="scope"> {{ scope.row.estimateTime }}{{ formatTimeUnit(scope.row.timeUnit) }} </template>
          </el-table-column>
          <el-table-column prop="deliveryTime" label="可送时间段" align="center" width="200"> </el-table-column>
          <el-table-column prop="businessRemindTime" label="商户提醒时间(分)" align="center" width="140"> </el-table-column>
          <el-table-column prop="waiterRemindTime" label="服务员提醒时间(分)" align="center" width="140"> </el-table-column>
        </el-table>
      </el-row>

      <div class="title" v-if="dataForm.serverType == 4 && !dataForm.specs.length">服务员工作时间</div>
      <el-row style="width: 96%; margin: 0 auto" v-if="dataForm.serverType == 4 && !dataForm.specs.length">
        <WaiterTime :waiters="dataForm.waiters" :relationWaiters="dataForm.relationWaiters"></WaiterTime>
      </el-row>

      <div class="title">货品视频图片与规格</div>
      <el-row style="width: 96%; margin: 0 auto">
        <div class="flex-box">
          <div class="server-img">
            <span class="label">*</span>
            货品视频图片
          </div>
          <div class="btn-wrapper">
            <el-checkbox v-model="dataForm.imagesSave"> 同步上传至公共图库 </el-checkbox>
          </div>
          <div class="btn-wrapper">
            <el-button type="danger" size="mini" @click="showImageSelectDialog = true">复制公共图库</el-button>
          </div>
        </div>
        <UploadOssFile :list="fileList" @getImgVideo="getImgVideo" folder="serverImg"></UploadOssFile>
        <GoodsSpec
          v-show="!dataForm.haskFlag"
          ref="goodsSpec"
          :info="dataForm"
          :specList="dataForm.specs"
          :tableList="dataForm.businessServerVariants"
          :subsidyAmountTableList="dataForm.subsidyAmountTableList"
          :mainImg="mainImg"
          folder="serverImg"
          :serverType="dataForm.serverType"
          @showSave="handleShowSave"
        >
        </GoodsSpec>
      </el-row>
      <div class="title">商品详情描述</div>
      <el-row style="width: 96%; margin: 0 auto">
        <div class="introduce">
          <div class="item">
            <div class="label">货品简介</div>
            <el-input rows="4" type="textarea" maxlength="200" show-word-limit v-model="dataForm.introduce" placeholder="请输入简介"></el-input>
          </div>
          <div class="item">
            <div class="label">备注</div>
            <el-input rows="4" type="textarea" v-model="dataForm.remark" placeholder="请输入备注"></el-input>
          </div>
        </div>
        <RichEditor :richText="dataForm.describes" @getRichText="getRichText"></RichEditor>
      </el-row>
      <el-row class="bottom" :style="{ width: !$store.getters.sidebar.opened ? 'calc(100vw - 87px)' : 'calc(100vw - 239px)' }">
        <div class="wrapper">
          <div class="back" @click="returnList">返回</div>
          <div v-if="dataForm.serverId" :style="{ 'border-top-right-radius': showSave ? '' : '5px', 'border-bottom-right-radius': showSave ? '' : '5px' }" @click="sureClick(1)">保存并同步修改经营产品</div>
          <div v-if="showSave" class="save" style="border-left: 0" @click="sureClick()">保存</div>
        </div>
      </el-row>
    </div>
    <ImageSelect :show="showImageSelectDialog" folder="serverImg" :limit="limitNum" @cancel="showImageSelectDialog = false" @getUrlList="getUrlList"></ImageSelect>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import BusinessServerApi from '@/api/goods/businessServer';
import BusinessApi from '@/api/business/business';
import ServerClassifyApi from '@/api/server/serverClassify';
import BusinessDepartApi from '@/api/business/depart';
import UploadImg from '../../components/UploadImg.vue';
import GoodsSpec from '../../components/GoodsSpec.vue';
import RichEditor from '../../components/RichEditor.vue';
import UploadOssFile from '../../components/UploadOssFile.vue';
import ImageSelect from '../../components/ImageSelect.vue';
import TimeTemplateApi from '@/api/goods/timeTemplate';
import WaiterTime from '@/components/WaiterTime';
import DoctorApi from '@/api/institution/doctor';
import WaiterApi from '@/api/business/waiter';
import { ESubsidyAmount } from '@/enum';
export default {
  data() {
    return {
      cascaderKey: 1,
      userInfo: '',
      dataForm: {
        relationAmountType: [],
        serverId: '',
        //sort:"",
        businessId: '',
        classifyIds: [],
        serverType: 1,
        dockingType: '',
        dockingFlag: 1,
        deposit: '',
        name: '',
        departIds: [],
        introduce: '',
        stock: '',
        describes: '',
        businessConfirmWay: 1, // 1.手动确认不管支不支付(默认值,手动派单) 2.自动确认不管支不支付 (包含自动派单) 3.支付后自动确认 (包含自动派单)
        visitFlag: 1, //是否上门，1代表是
        shopFlag: 0, //是否到店，1代表是，0代表不是
        remoteFlag: 0, //是否远程，1代表是，0代表不是
        fastFlag: 0, //紧急通知
        backFlag: 1, //是否必须归还，1代表是，0代表不是
        huskFlag: 0, //是否为空包产品 1表示是，2表示不是
        deliveryFlag: 0, //是否需配送费
        packageFlag: 1, //包装费计算方式(1.独立包装费(默认) 2.合并包装费)
        price: '',
        discount: '',
        externalDiscount: '',
        salePrice: '',
        marketPrice: '',
        costPrice: '',
        deliveryFee: '',
        packageFee: '',
        remark: '',
        specs: [],
        businessServerVariants: [],
        variantState: 1,
        serverCode: '',
        businessServerImages: [],
        imagesSave: false,
        businessClassifyIds: [],
        ghModelId: '',
        goodsHours: [],
        doctorId: '',
        itemCode: '',
        itemName: '',
        specDisplayType: 0, // 多规格展示方式 0代表默认 1页面展示
        waiters: [],
        relationWaiters: [
          // {
          //   waiterId:"",
          //   waiterName:"",
          //   prepareTime:"",// 准备时间
          //   serviceTime:""// 结束时间
          // }
        ],
        subsidyAmountTableList: [{ discountold: '', rebate0ld: '', discountPmc: '', rebatePmc: '' }],
      },
      fileList: [],
      businessList: [],
      businessClassifyList: [],
      treeThreeServerList: [],
      waiterList: [],
      doctorList: [],
      loadingIns: false,
      roleRules: {
        businessId: [{ required: true, message: '请选择商户', trigger: 'change' }],
        classifyIds: [{ required: true, message: '请选择货品分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入货品名称', trigger: 'blur' }],
      },
      selectRoleRules: {
        stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
        price: [{ required: true, type: 'number', message: '请输入平台原价', trigger: 'blur' }],
        salePrice: [{ required: true, type: 'number', message: '请输入平台售价', trigger: 'blur' }],
        discount: [{ required: true, type: 'number', message: '请输入商户折扣比例', trigger: 'blur' }],
        costPrice: [{ required: true, type: 'number', message: '请输入成本价', trigger: 'blur' }],
        marketPrice: [{ required: true, type: 'number', message: '请输入商户原价', trigger: 'blur' }],
      },
      showImageSelectDialog: false,
      limit: 5,
      loading: false,
      departList: [],
      goodsHoursList: [],
      showSave: true, //如果规格列表改变了那么保存就不显示
      // waiterRelationList:[], // 选择服务员生成的列表数据
      subsidyAmountList: ESubsidyAmount,
    };
  },
  components: {
    UploadImg,
    GoodsSpec,
    RichEditor,
    UploadOssFile,
    ImageSelect,
    WaiterTime,
  },
  computed: {
    mainImg() {
      let val = this.dataForm.businessServerImages.find((item) => item.mainFlag);
      return val ? val.url : '';
    },
    limitNum() {
      return this.limit - this.dataForm.businessServerImages.length;
    },
    // businessClassifyNames(){
    //   return this.businessClassifyList.filter(item=>this.dataForm.businessClassifyIds.some(item2=>item2==item.id)).map(item=>item.name)
    // },
    specDisplayType() {
      if (this.dataForm.specs.length == 1) {
        return false;
      } else {
        this.dataForm.specDisplayType = 0;
        return true;
      }
    },
  },
  mounted() {
    this.init();
  },
  watch: {
    treeThreeServerList() {
      this.cascaderKey++;
    },
    'dataForm.serverType': {
      handler(val) {
        if (val == 3) {
          this.roleRules.deposit = { required: true, type: 'number', message: '请输入押金', trigger: 'blur' };
        } else {
          this.$delete(this.roleRules, 'deposit');
        }

        if (val == 4 && !this.dataForm.specs.length) {
          this.roleRules.waiters = { required: true, message: '请选择服务员', trigger: 'change' };
        } else {
          this.$delete(this.roleRules, 'waiters');
        }

        if (val == 15) {
          const { dataForm } = this;
          dataForm.price = 100;
          // dataForm.discount = 99.72
          dataForm.salePrice = 100;
          dataForm.marketPrice = 100;
          // dataForm.costPrice = 100
        }

        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate();
          this.$refs.dataForm2.clearValidate();
        });
      },
      immediate: true,
    },
    'dataForm.huskFlag': {
      handler(val) {
        const { dataForm, roleRules, selectRoleRules } = this;
        if (val) {
          this.roleRules = Object.assign(roleRules, selectRoleRules);
          dataForm.stock = 9999;
          dataForm.price = 0;
          dataForm.salePrice = 0;
          dataForm.discount = 0;
          dataForm.costPrice = 0;
          dataForm.marketPrice = 0;
          dataForm.packageFee = 0;
          dataForm.packageFlag = 1;
          dataForm.deliveryFlag = 0;
          this.$delete(this.roleRules, 'deposit');
          dataForm.serverType = 1;
        } else {
          const keys = Object.keys(selectRoleRules);
          Object.keys(this.roleRules).forEach((item) => {
            if (keys.includes(item)) {
              this.$delete(roleRules, item);
            }
          });
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate();
          this.$refs.dataForm2.clearValidate();
        });
      },
      immediate: true,
    },
    // "dataForm.waiters":{
    //   handler(val){
    //     console.log(val)
    //   },
    //   immediate:true
    // }
  },
  methods: {
    async init() {
      this.getBusinessList();
      await this.getWaiterList();
      if (this.$route.query.id) {
        this.dataForm.serverId = this.$route.query.id;
        this.getData();
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      const res = await BusinessServerApi.getBusinessServerInfo({ id: this.dataForm.serverId });
      const data = res.data;
      // 这里需要将二三级分类id变为数组
      const classifyIds = [];
      data.serverClassifyId ? classifyIds.push(data.serverClassifyId) : '';
      data.thirdClassifyId ? classifyIds.push(data.thirdClassifyId) : '';
      data.classifyIds = classifyIds;

      // 将四级部门合并为数组
      const departIds = [];
      data.departId ? departIds.push(data.departId) : '';
      data.firstDepartId ? departIds.push(data.firstDepartId) : '';
      data.secondDepartId ? departIds.push(data.secondDepartId) : '';
      data.thirdDepartId ? departIds.push(data.thirdDepartId) : '';
      data.departIds = departIds;
      data.relationAmountType = data.relationAmountType ? data.relationAmountType.split(',').map((item) => Number(item)) : [];

      // 存在服务员就添加
      data.relationWaiters && (data.waiters = data.relationWaiters.map((item) => ({ id: item.waiterId, name: item.waiterName })));

      // 如果存在商户分类就需要获取
      data.businessClassifyIds = (data.businessClassifies || []).map((item) => item.id);

      // 处理规格列表
      data.businessServerVariants && data.businessServerVariants.forEach((item) => (item.moreImg = item.moreImg ? item.moreImg.split(',') : []));
      if (data.businessServerVariants) {
        data.relationAmountList.forEach((item, index) => {
          data.businessServerVariants[index] = { ...data.businessServerVariants[index], ...item };
        });
      } else {
        data.subsidyAmountTableList = data.relationAmountList.length > 0 ? data.relationAmountList : [{ discountOld: '', rebateOld: '', discountPmc: '', rebatePmc: '' }];
      }
      this.fileList = JSON.parse(JSON.stringify(data.businessServerImages || []));
      this.$Utils.bindingBean(this.dataForm, data);

      this.getTreeThreeServerList();
      this.getDepartList();
      this.getGoodsHoursList();
      await this.getBusinessClassifyList();

      // 存在商户分类就获取关联医生
      if (data.businessClassifyIds.length > 0) this.getDoctorList();
    },
    // 获取服务员
    async getWaiterList() {
      const { data } = await WaiterApi.listIdName({ jobType: 1 });
      this.waiterList = data || [];
    },
    getDepartList() {
      BusinessDepartApi.listMangerTree({ businessId: this.dataForm.businessId }).then((res) => {
        this.setDisabled(res.data);
        this.departList = res.data;
      });
    },
    setDisabled(list) {
      list.forEach((item) => {
        if (!item.power) {
          item.disabled = true;
        }
        if (item.children) {
          this.setDisabled(item.children);
        }
      });
    },
    async getDoctorList() {
      let { businessClassifyIds } = this.dataForm;
      businessClassifyIds = businessClassifyIds.toString();
      if (!businessClassifyIds) return;
      const { data } = await DoctorApi.getDoctorNames({ businessClassifyIds });
      this.doctorList = data || [];
    },
    handleGhModelIdChange() {
      const { dataForm, goodsHoursList } = this;
      dataForm.goodsHours = [];
      if (!dataForm.ghModelId) return;
      const val = goodsHoursList.find((item) => item.modelId == dataForm.ghModelId);
      if (val) {
        dataForm.goodsHours = val.relations;
      }
    },
    handleWaiterIdsChange() {
      // const {dataForm:{waiters,relationWaiters},waiterList}  = this
      // const arr = waiters.map(item=>({
      //   waiterId:item.id,
      //   waiterName:item.name,
      //   timeRange:null
      // }))
      // relationWaiters.length&&arr.forEach(item=>{
      //   relationWaiters.find(item2=>item2.waiterId==item.waiterId&&(item.timeRange = item2.timeRange))
      // })
      // this.dataForm.relationWaiters = arr
    },
    formatTimeUnit(cell) {
      if (cell === 1) {
        return '分钟';
      } else if (cell == 2) {
        return '时';
      } else {
        return '';
      }
    },
    getGoodsHoursList() {
      TimeTemplateApi.listIdName({ businessId: this.dataForm.businessId }).then((res) => {
        this.goodsHoursList = res.data;
      });
    },
    async getBusinessClassifyList() {
      const res = await BusinessServerApi.classifyListIdName({ businessId: this.dataForm.businessId });
      this.businessClassifyList = res.data;
      // this.getBusinessClassifyStyle()
      // this.handleBusinessClassifyChange()
    },
    getUrlList(val) {
      this.fileList = JSON.parse(JSON.stringify(this.dataForm.businessServerImages.concat(val)));
      this.showImageSelectDialog = false;
    },
    getRichText(val) {
      this.dataForm.describes = val;
    },
    handleBusinessIdChange() {
      this.dataForm.doctorId = '';
      this.dataForm.doctorList = [];
      this.dataForm.classifyIds = [];
      this.treeThreeServerList = [];
      this.dataForm.departIds = [];
      this.goodsHoursList = [];
      this.dataForm.ghModelId = '';
      this.dataForm.goodsHours = [];
      this.dataForm.businessClassifyIds = [];
      this.businessClassifyList = [];
      this.departList = [];
      if (this.dataForm.businessId) {
        this.getTreeThreeServerList();
        this.getDepartList();
        this.getGoodsHoursList();
        this.getBusinessClassifyList();
      }
      // this.handleBusinessClassifyChange()
    },
    // 商户分类改变
    handleBusinessClassifyChange() {
      this.dataForm.doctorId = '';
      this.doctorList = [];
      if (this.dataForm.businessClassifyIds.length > 0) {
        this.getDoctorList();
      }
      // this.getBusinessClassifyStyle()
    },
    // getBusinessClassifyStyle(){
    //   this.$nextTick(() => {
    //     const {businessClassifyList, dataForm} = this
    //     const els = document.querySelectorAll('.business-classify_select .el-select__tags-text')
    //     dataForm.businessClassifyIds.forEach((item, index) => {
    //       const obj = businessClassifyList.find(item2 => item2.id == item)
    //       els[index].innerHTML = obj.name
    //     })
    //   })
    // },
    // 获取上传的文件列表
    getImgVideo(val) {
      this.dataForm.businessServerImages = val;
    },
    // 获取商户列表
    async getBusinessList() {
      const res = await BusinessApi.listIdNameVo();
      this.businessList = res.data;
    },
    // 获取二三级服务列表
    getTreeThreeServerList() {
      let params = {
        level: 2,
        businessId: this.dataForm.businessId,
      };
      ServerClassifyApi.listServerClassify(params).then((res) => {
        this.treeThreeServerList = res.data;
      });
    },
    handleShowSave(bool) {
      // 修改了规格且是编辑那么就不显示保存按钮
      if (this.dataForm.serverId) {
        this.showSave = bool;
      }
    },
    handleFlagChange(val) {
      const { visitFlag, shopFlag, remoteFlag } = this.dataForm;
      switch (val) {
        case 1:
          if (visitFlag) {
            this.dataForm.shopFlag = 0;
            this.dataForm.remoteFlag = 0;
          }
          break;
        case 2:
          if (shopFlag) {
            this.dataForm.visitFlag = 0;
            this.dataForm.remoteFlag = 0;
          }
          break;
        case 3:
          if (remoteFlag) {
            this.dataForm.shopFlag = 0;
            this.dataForm.visitFlag = 0;
          }
          break;
      }
    },
    checkData() {
      // let flag = this.dataForm.businessServerVariants.length > 0

      // 不是空包产品才检测规格
      if (!this.dataForm.huskFlag && !this.$refs.goodsSpec.checkSpec()) return;

      if (this.dataForm.businessServerVariants.length) {
        this.dataForm.variantState = 2;
        this.businessServerVariants = JSON.parse(JSON.stringify(this.dataForm.businessServerVariants));
        this.businessServerVariants.forEach((item) => (item.moreImg = item.moreImg.join(',')));
      } else {
        this.dataForm.variantState = 1;
      }

      if (this.dataForm.dockingFlag == 2 && !this.dataForm.dockingType) {
        this.$message.error('对接类型不能为空');
        return false;
      }

      if (!this.dataForm.businessServerImages.some((item) => item.type == 1)) {
        this.$message.error('请至少选择一张货品图片');
        return false;
      }

      if (!this.dataForm.businessServerImages.some((item) => item.type == 1 && item.mainFlag == 1)) {
        this.$message.error('请至少选择一张产品主图');
        return false;
      }

      if (this.dataForm.goodsHours.length > 0) {
        this.goodsHours = this.dataForm.goodsHours.map((item) => item.beginHours + '-' + item.endHours).toString();
      }

      if (this.dataForm.serverType == 4 && !this.dataForm.specs.length) {
        for (let item of this.dataForm.relationWaiters) {
          if (!item.prepareTime || !item.serviceTime) {
            this.$message.error('请把服务员工作时间填写完整');
            return;
          }
        }
      }

      return true;
    },
    async sureClick(isUpdate) {
      if (!this.checkData()) return;
      const res = await Promise.all([this.$refs.dataForm.validate(), this.$refs.dataForm2.validate()]);
      if (!res) return;
      this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
        if (this.dataForm.serverId) {
          this.editData(isUpdate);
        } else {
          this.addData();
        }
      });
    },
    // 商户原价改变
    handleMarketPriceBlur() {
      const { marketPrice, discount, costPrice } = this.dataForm;
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = '';
        this.dataForm.discount = '';
        this.$message.error('商户原价不能小于成本价');
        return;
      }

      this.dataForm.costPrice = parseFloat(((marketPrice * discount) / 100).toFixed(4));
    },
    // 商户折扣比例改变
    handleDiscountBlur() {
      const { marketPrice, discount } = this.dataForm;
      this.dataForm.costPrice = parseFloat(((marketPrice * discount) / 100).toFixed(4));
    },
    handleCostBlur() {
      const { costPrice, marketPrice } = this.dataForm;
      if (costPrice == 0) {
        return;
      }
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = '';
        this.dataForm.discount = '';
        this.$message.error('成本价不能大于商户原价');
        return;
      }
      this.dataForm.discount = parseFloat(((costPrice / marketPrice) * 100).toFixed(2));
    },
    handleMoneyInput(flag) {
      if (!flag) {
        // 只保留两位小数
        this.dataForm.price = parseFloat(parseFloat(this.dataForm.price).toFixed(2));
        !this.dataForm.price ? (this.dataForm.price = 0) : '';
      } else if (flag == 1) {
        this.dataForm.salePrice = parseFloat(parseFloat(this.dataForm.salePrice).toFixed(2));
        !this.dataForm.salePrice ? (this.dataForm.salePrice = 0) : '';
      } else if (flag == 2) {
        // 只保留两位小数
        this.dataForm.costPrice = parseFloat(parseFloat(this.dataForm.costPrice).toFixed(4));
        !this.dataForm.costPrice ? (this.dataForm.costPrice = 0) : '';
      } else if (flag == 3) {
        // 只保留两位小数
        this.dataForm.packageFee = parseFloat(parseFloat(this.dataForm.packageFee).toFixed(2));
        !this.dataForm.packageFee ? (this.dataForm.packageFee = 0) : '';
      } else if (flag == 4) {
        this.dataForm.deposit = parseFloat(parseFloat(this.dataForm.deposit).toFixed(2));
        !this.dataForm.deposit ? (this.dataForm.deposit = 0) : '';
      } else if (flag == 5) {
        this.dataForm.marketPrice = parseFloat(parseFloat(this.dataForm.marketPrice).toFixed(2));
        !this.dataForm.marketPrice ? (this.dataForm.marketPrice = 0) : '';
      }
    },
    // 平台比例输入的时候
    handleDiscountInput() {
      this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2));
      if (this.dataForm.discount && this.dataForm.discount > 99.72) {
        this.dataForm.discount = 0;
        this.$message.error('商户折扣比例只能是0-99.72之间');
      } else if (this.dataForm.discount) {
        this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2));
      } else {
        this.dataForm.discount = 0;
      }
    },
    handleExternalDiscountInput() {
      this.dataForm.externalDiscount = parseFloat(parseFloat(this.dataForm.externalDiscount).toFixed(2));
      if (this.dataForm.externalDiscount && this.dataForm.externalDiscount > 99.72) {
        this.dataForm.externalDiscount = 0;
        this.$message.error('商户折扣比例只能是0-99.72之间');
      } else if (this.dataForm.externalDiscount) {
        this.dataForm.externalDiscount = parseFloat(parseFloat(this.dataForm.externalDiscount).toFixed(2));
      } else {
        this.dataForm.externalDiscount = 0;
      }
    },
    handleStockInput() {
      this.dataForm.stock = this.dataForm.stock.replace(/[^0-9]|^0/g, '');
    },
    addData() {
      let param = {
        serverType: this.dataForm.serverType,
        deposit: this.dataForm.serverType == 3 ? this.dataForm.deposit : '',
        businessId: this.dataForm.businessId,
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : '',
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : '',
        businessClassifyIds: this.dataForm.businessClassifyIds,
        doctorId: this.dataForm.doctorId,
        itemCode: this.dataForm.itemCode,
        itemName: this.dataForm.itemName,
        name: this.dataForm.name,
        departId: this.dataForm.departIds[0] || '',
        firstDepartId: this.dataForm.departIds[1] || '',
        secondDepartId: this.dataForm.departIds[2] || '',
        thirdDepartId: this.dataForm.departIds[3] || '',
        businessServerImages: this.dataForm.businessServerImages,
        introduce: this.dataForm.introduce,
        describes: this.dataForm.describes,
        visitFlag: this.dataForm.visitFlag,
        businessConfirmWay: this.dataForm.businessConfirmWay,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        backFlag: this.dataForm.serverType == 3 ? this.dataForm.backFlag : '',
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag: this.dataForm.packageFlag,
        price: this.dataForm.price,
        discount: this.dataForm.discount,
        externalDiscount: this.dataForm.externalDiscount,
        salePrice: this.dataForm.salePrice,
        deliveryFee: this.dataForm.deliveryFee,
        packageFee: this.dataForm.packageFee,
        costPrice: this.dataForm.costPrice,
        marketPrice: this.dataForm.marketPrice,
        remark: this.dataForm.remark,
        huskFlag: this.dataForm.huskFlag,
        // specs: this.dataForm.specs,
        // businessServerVariants: this.dataForm.businessServerVariants,
        imagesSave: this.dataForm.imagesSave,
        stock: this.dataForm.stock,
        goodsHours: this.dataForm.goodsHours,
        ghModelId: this.dataForm.ghModelId,
        dockingType: this.dataForm.dockingType,
        dockingFlag: this.dataForm.dockingFlag,
        specDisplayType: this.dataForm.specDisplayType,
        relationAmountType: this.dataForm.relationAmountType.toString(),
      };
      if (!param.huskFlag) {
        param.businessServerVariants = this.businessServerVariants;
        param.specs = this.dataForm.specs;
      }
      // if (this.userInfo.userRole == 3) {
      //   param.businessId = this.userInfo.relationRoleId
      // }
      this.loading = true;
      if (param.businessServerVariants) {
        param.relationAmountList = param.businessServerVariants.map((item) => {
          return { sku: item.sku, discountOld: item.discountOld, rebateOld: item.rebateOld, discountPmc: item.discountPmc, rebatePmc: item.rebatePmc };
        });
      } else {
        param.relationAmountList = this.dataForm.subsidyAmountTableList;
      }
      BusinessServerApi.addBusinessServer(param)
        .then((res) => {
          this.$Utils.notifySuccess();
          this.returnList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    editData(isUpdate) {
      let param = {
        //sort:this.dataForm.sort?this.dataForm.sort:999,
        serverId: this.dataForm.serverId,
        businessId: this.dataForm.businessId,
        serverType: this.dataForm.serverType,
        deposit: this.dataForm.serverType == 3 ? this.dataForm.deposit : '',
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : '',
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : '',
        businessClassifyIds: this.dataForm.businessClassifyIds,
        doctorId: this.dataForm.doctorId,
        itemCode: this.dataForm.itemCode,
        itemName: this.dataForm.itemName,
        name: this.dataForm.name,
        departId: this.dataForm.departIds[0] || '',
        firstDepartId: this.dataForm.departIds[1] || '',
        secondDepartId: this.dataForm.departIds[2] || '',
        thirdDepartId: this.dataForm.departIds[3] || '',
        businessServerImages: this.dataForm.businessServerImages,
        introduce: this.dataForm.introduce,
        describes: this.dataForm.describes,
        visitFlag: this.dataForm.visitFlag,
        businessConfirmWay: this.dataForm.businessConfirmWay,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        backFlag: this.dataForm.serverType == 3 ? this.dataForm.backFlag : '',
        huskFlag: this.dataForm.huskFlag,
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag: this.dataForm.packageFlag,
        price: this.dataForm.price,
        discount: this.dataForm.discount,
        externalDiscount: this.dataForm.externalDiscount,
        costPrice: this.dataForm.costPrice,
        salePrice: this.dataForm.salePrice,
        deliveryFee: this.dataForm.deliveryFee,
        packageFee: this.dataForm.packageFee,
        marketPrice: this.dataForm.marketPrice,
        remark: this.dataForm.remark,
        serverCode: this.dataForm.serverCode,
        // specs: this.dataForm.specs,
        // businessServerVariants: this.dataForm.businessServerVariants,
        imagesSave: this.dataForm.imagesSave,
        stock: this.dataForm.stock,
        goodsHours: this.dataForm.goodsHours,
        ghModelId: this.dataForm.ghModelId,
        dockingType: this.dataForm.dockingType,
        dockingFlag: this.dataForm.dockingFlag,
        specDisplayType: this.dataForm.specDisplayType,
        relationAmountType: this.dataForm.relationAmountType.toString(),
      };
      // if (this.userInfo.userRole == 3) {
      //   param.businessId = this.userInfo.relationRoleId
      // }
      // 是否一键同步修改经营货品
      if (isUpdate) {
        param.update = isUpdate;
      }
      if (!param.huskFlag) {
        param.businessServerVariants = this.businessServerVariants;
        param.specs = this.dataForm.specs;
      }
      this.loading = true;
      if (param.businessServerVariants) {
        param.relationAmountList = param.businessServerVariants.map((item) => {
          return { sku: item.sku, discountOld: item.discountOld, rebateOld: item.rebateOld, discountPmc: item.discountPmc, rebatePmc: item.rebatePmc };
        });
      } else {
        param.relationAmountList = this.dataForm.subsidyAmountTableList;
      }
      BusinessServerApi.editBusinessServer(param)
        .then((data) => {
          this.$Utils.notifySuccess();
          this.returnList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/goods/businessServerManagement' });
    },
  },
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/views/serverAdd.scss';
</style>
<style lang="scss" scoped>
.flex-box {
  display: flex;
  align-items: center;

  & > div {
    margin-right: 10px;
  }

  .server-img {
    position: relative;
    font-size: 14px;

    .label {
      color: red;
      position: absolute;
      top: 0;
      left: -12px;
    }
  }
}

.introduce {
  margin-bottom: 10px;
  font-size: 14px;
  display: flex;
  width: 1000px;
  justify-content: space-between;

  .item {
    width: 46%;
    display: flex;
    text-align: end;

    .label {
      width: 80px;
      padding-right: 7px;
    }
  }
}
</style>
